package cn.demoncat.util.redis.config;

import cn.demoncat.util.lang.constant.StringConstant;
import cn.demoncat.util.web.config.AppProperties;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Redis缓存隔离器
 *
 * 配置：spring.application.isolator
 * 场景：多个系统，使用同一个Redis，为了防止KEY冲突，分别对缓存的KEY添加前缀来标识
 * 使用：判断spring.application.isolator非空时，添加前缀 redisIsolator.getPrefix()
 *
 * @author 延晓磊
 * @since 2022年09月27日
 */
@Component
public class RedisIsolator {

    @Resource
    private AppProperties appProperties;

    /**
     * 缓存key前缀
     */
    private String prefix = null;

    /**
     * 获取缓存KEY
     *
     * @param key
     * @return
     */
    public String getKey(String key){
        return this.getPrefix().isEmpty() ? key : (key.startsWith(this.getPrefix()) ? key : (this.getPrefix() + key));
    }

    /**
     * 获取缓存KEY
     *
     * @param keys
     * @return
     */
    public Collection<String> getKeys(Collection<String> keys){
        if (this.getPrefix().isEmpty() || CollectionUtils.isEmpty(keys)) {
            return keys;
        }else{
            return  keys.stream().map(key -> key.startsWith(this.getPrefix()) ? key : (this.getPrefix() + key)).collect(Collectors.toList());
        }
    }

    /**
     * 获取缓存KEY
     *
     * @param keys
     * @return
     */
    public List<String> getKeys(List<String> keys){
        if (this.getPrefix().isEmpty() || CollectionUtils.isEmpty(keys) || keys.get(0).startsWith(this.getPrefix())) {
            return keys;
        }else{
            return keys.stream().map(key -> this.getPrefix() + key).collect(Collectors.toList());
        }
    }

    /**
     * 获取缓存KEY
     *
     * @param kvs
     * @return
     */
    public Map<String,String> getKeyVals(Map<String,String> kvs){
        if (this.getPrefix().isEmpty() || MapUtils.isEmpty(kvs)) {
            return kvs;
        }else{
            Map<String,String> map = new HashMap<>();
            for (String key : kvs.keySet()) {
                map.put(this.getPrefix() + key, kvs.get(key));
            }
            return map;
        }
    }

    /**
     * 获取缓存前缀
     *
     * @return
     *
     * @author 延晓磊
     * @since 2023年04月23日
     */
    public String getPrefix(){
        if (this.prefix == null) {
            if (StringUtils.isBlank(appProperties.getIsolator())) {
                // ""
                this.prefix = StringConstant.EMPTY;
            }else{
                // isolator-
                this.prefix = appProperties.getIsolator().toUpperCase() + StringConstant.COLON;
            }
        }
        return this.prefix;
    }
}
